#include "daemon_sub_process.h"
#include "wait.h"
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/reboot.h>
#include <signal.h>
/**
 * 初始化子进程
 */

sub_process_t *daemon_sub_process_init(char *cmd)
{
    sub_process_t *sub_process = (sub_process_t *)malloc(sizeof(sub_process_t));
    sub_process->cmd = cmd;
    sub_process->pid = -1;
    sub_process->fail_count = 0;
    return sub_process;
}
/**
 * 检测或启动子进程
 */
int daemon_sub_process_check_and_start(sub_process_t *sub_process)
{
    //判断是否是异常结束的问题
    int over_status = 0;
    // 如果子进程没有启动 或者 子进程已经结束
    if (sub_process->pid == -1 || waitpid(sub_process->pid, &over_status, WNOHANG) == -1)
    {
        // 如果是异常结束
        if (over_status != 0)
        {

            sub_process->fail_count++;
            // 超过最大失败次数重启系统
            if (sub_process->fail_count > MAX_SUB_FAIL_COUNT)
            {
                reboot(RB_AUTOBOOT);
                //如果是异常结束就不向下执行了
            }
        }
        // 启动子进程
        sub_process->pid = fork();
        if (sub_process->pid == 0)
        {
            // 子进程
            char *proc = "/usr/bin/gateway"; // 启动子进程的命令
                                             // 名字              //ota version app 等命令
            char *args[] = {"/usr/bin/gateway", sub_process->cmd, NULL};
            char *env[] = {NULL};

            int ret = execve(proc, args, env);
            if (ret == -1)
            {
                perror("execve");
                _exit(EXIT_FAILURE);
            }
        }
    }
    return 0;
}

/**
 * 销毁子进程
 */
void daemon_sub_process_destroy(sub_process_t *sub_process){
    if(sub_process){
        if(sub_process->pid>0){
            kill(sub_process->pid,SIGTERM);
            //等待子进程结束
            waitpid(sub_process->pid,NULL,0);
        }
        //释放子线程结构体
        free(sub_process);
    }
}